package com.zmc.admin.controller.system;

import com.zmc.admin.infrastructure.bean.vo.dict.SysDictDataVo;
import com.zmc.admin.infrastructure.entity.SysDictDataEntity;
import com.zmc.admin.infrastructure.bean.query.SysDictDataQuery;
import com.zmc.admin.infrastructure.service.SysDictDataService;
import com.zmc.common.annotation.PreventRepeatSubmit;
import com.zmc.common.enums.RequestSourceEnum;
import com.zmc.common.utils.PageUtils;
import com.zmc.common.utils.R;
import com.zmc.common.utils.StringUtils;
import com.zmc.common.utils.poi.ExcelUtil;
import com.zmc.common.utils.token.AuthTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据字典信息
 * @author zmc
 */
@RestController
@RequestMapping("/dict/data")
public class SysDictDataController {
    @Autowired
    private SysDictDataService dictDataService;

    @Autowired
    private AuthTokenService authTokenService;

    @PostMapping("/list")
    public R list(@RequestBody SysDictDataQuery query) {
        PageUtils page = dictDataService.queryPage(query);
        return R.page(page);
    }

    @PostMapping("/dictCode")
    public R getInfo(@RequestBody SysDictDataVo vo) {
        return R.ok(dictDataService.getById(vo.getDictCode()));
    }

    @PostMapping(value = "/type")
    public R dictType(@RequestBody SysDictDataVo vo) {
        List<SysDictDataEntity> data = dictDataService.selectDictDataByType(vo.getDictType());
        if (StringUtils.isNull(data)) {
            data = new ArrayList<SysDictDataEntity>();
        }
        return R.ok(data);
    }


    @PostMapping("/export")
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public void export(HttpServletResponse response, SysDictDataQuery query) {
        List<SysDictDataEntity> list = dictDataService.selectDictDataList(query);
        ExcelUtil<SysDictDataEntity> util = new ExcelUtil<>(SysDictDataEntity.class);
        util.exportExcel(response, list, "字典数据");
    }

    @PostMapping("/add")
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public R add(@RequestBody SysDictDataEntity dict) {
        dict.setCreateBy(authTokenService.getUserInfo().getUsername());
        dictDataService.save(dict);
        return R.ok();
    }

    @PostMapping("/update")
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public R edit(@RequestBody SysDictDataEntity dict) {
        dict.setUpdateBy(authTokenService.getUserInfo().getUsername());
        dictDataService.updateById(dict);
        return R.ok();
    }

    @PostMapping("/delete")
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public R remove(@RequestBody SysDictDataVo vo) {
        dictDataService.removeById(vo.getDictCode());
        return R.ok();
    }
}
